/*
 * @lc app=leetcode.cn id=701 lang=typescript
 *
 * [701] 二叉搜索树中的插入操作
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
    const node = new TreeNode(val);
    if (!root) {
        return node
    }

    let parentNode = new TreeNode();
    let currentNode = root;

    while (currentNode) {
        if (currentNode.val > val) {
            parentNode = currentNode;
            currentNode = parentNode.left
        } else {
            parentNode = currentNode;
            currentNode = parentNode.right
        }
    }

    if (parentNode.val > val) {
        parentNode.left = node;
    } else {
        parentNode.right = node;
    }
    return root;
};

// @lc code=end

